<!DOCTYPE html>
<meta charset="utf-8">
<title>Navigation Preload Response after GC shouldn't cause crash.</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="../resources/test-helpers.js"></script>
<script>

// This test simulates the following situation:
//  1. The browser process sends the navigation preload request to the server.
//  2. In SW's FetchEvent handler:
//   2.1 Executes GC with internals.collectGarbage().
//   2.2 Sleeps 100 ms not to cancel the navigation request before the server
//       returns the preload response.
//   2.3 Returns a dummy response "hello".
//  3. The server returns the preload response, and the SW recieves it via the
//     browser process.
// Before https://crbug.com/702527#c9, |m_pendingPreloadFetchEvents| of
// ServiceWorkerGlobalScopeProxy is accidentally cleared in the GC. So the SW
// crashed when it receives the preload response.
promise_test(t => {
    var script = 'resources/preload-response-after-gc-worker.js';
    var scope = 'resources/preload-response-after-gc-scope.html';
    return service_worker_unregister_and_register(t, script, scope)
      .then(registration => {
          add_completion_callback(_ => registration.unregister());
          var worker = registration.installing;
          return wait_for_state(t, worker, 'activated');
        })
      .then(_ => with_iframe(scope))
      .then(frame => {
          assert_equals(frame.contentWindow.document.body.innerText, 'hello');
          // Wait for a while to ensure that the SW receives the response.
          return new Promise(resolve => setTimeout(resolve, 100));
        });
  }, 'Navigation Preload Response after GC shouldn\'t cause crash');

</script>
